package com.yanfei.zero.infrastructure.threads;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DirectAssignmentThreadPool {
    public static void main(String[] args) {
    	ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1));
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            	if(r instanceof Task) {
            		Task tsk=(Task)r;
            		System.out.println("任务被拒绝：" +tsk.getId() );
            	}
                
                try {
                    // 直接分配给空闲线程执行
                    executor.execute(r);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        // 提交任务
        for (int i = 0; i < 20; i++) {
            executor.execute(new Task(i));
        }

//        // 关闭线程池
//        executor.shutdown();
//        try {
//            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
//                executor.shutdownNow();
//            }
//        } catch (InterruptedException e) {
//            executor.shutdownNow();
//        }
    }
}

class Task implements Runnable {
    private int id;
    public Task(int id) {
        this.id = id;
    }
    @Override
    public void run() {
        System.out.println("执行任务：" + id);
    }
    public int getId() {
    	return this.id;
    }
}
